/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller.bjxxclassmaterialproject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialProject;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialRange;
import cn.qidisoft.edu.hzjt.model.Employee;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.Student;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.IBjxxClassMaterialProjectService;
import cn.qidisoft.edu.hzjt.service.IBjxxClassMaterialRangeService;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.IOfDoingsService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author hhl
 * @version $Id: ProjectController.java, v 0.1 2018年10月23日 下午4:56:53 hhl Exp $
 */
@Controller
@RequestMapping(value = "bjxxClassMaterialProject")
public class BjxxClassMaterialProjectController {
    protected static final LoggerAdapter     LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);
    @Autowired
    private IBjxxClassMaterialProjectService bjxxClassMaterialProjectService;

    @Autowired
    private IBjxxClassMaterialRangeService   bjxxClassMaterialRangeService;

    @Autowired
    private ICommonService                   commonService;

    @Autowired
    private IOfDoingsService                 ofDoingsService;

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "bjxxClassMaterialProject/BjxxClassMaterialProjectList";
    }

    @RequestMapping(value = "/List")
    @ResponseBody
    public ResponseResult List(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "rows", required = false) String pageSize,
                               @RequestParam(value = "page", required = false) String currentPage,
                               BjxxClassMaterialProject data) {
        try {
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            PaginationBean<BjxxClassMaterialProject> paginationBean = bjxxClassMaterialProjectService
                .queryPageList(data, page);

            ResponseResult result = new ResponseResult();
            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<BjxxClassMaterialProject>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());
            return result;

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {

        return "bjxxClassMaterialProject/addBjxxClassMaterialProject";
    }

    @RequestMapping(value = "/updateToview", method = RequestMethod.GET)
    public String updateToview(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "id") Integer id) {
        try {
            BjxxClassMaterialProject data = new BjxxClassMaterialProject();
            data.setXmid(id);
            data = bjxxClassMaterialProjectService.queryByPK(data);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            if (data.getIssuetime() == null) {
            } else {
                data.setIssuetime1(sdf.format(data.getIssuetime()));
            }

            if (data.getDeadline() == null) {
            } else {
                data.setDeadline1(sdf.format(data.getDeadline()));
            }
            model.addAttribute("issued", data.getIssued());
            model.addAttribute("data", data);

            return "bjxxClassMaterialProject/updateBjxxClassMaterialProject";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public String details(ModelMap model, HttpServletRequest request,
                          @RequestParam(value = "id", required = false) Integer id,
                          @RequestParam(value = "gid", required = false) String gid) {
        try {

            BjxxClassMaterialProject data = new BjxxClassMaterialProject();
            data.setXmid(id);
            data.setGid(gid);
            data = bjxxClassMaterialProjectService.queryByPK(data);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            if (data.getIssuetime() == null) {
            } else {
                data.setIssuetime1(sdf.format(data.getIssuetime()));
            }

            if (data.getDeadline() == null) {
            } else {
                data.setDeadline1(sdf.format(data.getDeadline()));
            }
            model.addAttribute("issued", data.getIssued());
            model.addAttribute("data", data);

            java.util.List<Employee> List = commonService.queryStudentClassByBzr(new Student());
            model.addAttribute("List", List);

            return "bjxxClassMaterialProject/detailsBjxxClassMaterialProject2";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加目录信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "班级项目信息", moduleName = "班级项目管理", method = "新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(ModelMap model, HttpServletRequest request, BjxxClassMaterialProject data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setCreatorname(userEmployee.getUserid());
            data.setCreatorid(userEmployee.getUid());
            data.setCreatetime(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (data.getIssued() != null && data.getIssued() == true) {
                if (data.getIssuetime1() == null || data.getIssuetime1().equals("")) {
                    data.setIssuetime(new Date());
                }
            } else if (data.getIssuetime1() == null || data.getIssuetime1().equals("")) {

            } else {
                data.setIssuetime(sdf.parse(data.getIssuetime1()));
            }

            if (data.getDeadline1().equals("")) {

            } else {
                data.setDeadline(sdf.parse(data.getDeadline1()));
            }

            if (data.getIssued() == null || data.getIssued().equals("null")) {
                data.setIssued(false);
            }
            if (data.getStates() == null || data.getStates().equals("null")) {
                data.setStates(false);
            }
            String gid = bjxxClassMaterialProjectService.add(data, userEmployee.getUid());

            // BaseController.setParameter("msg", "保存成功");
            model.addAttribute("gid", gid);

            return "redirect:details";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "班级项目信息", moduleName = "班级项目管理", method = "新增")
    @RequestMapping(value = "/addSaveContinue", method = RequestMethod.POST)
    public String addSaveContinue(ModelMap model, HttpServletRequest request,
                                  BjxxClassMaterialProject data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setCreatorname(userEmployee.getUserid());
            data.setCreatorid(userEmployee.getUid());
            data.setCreatetime(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (data.getIssued() == true) {
                if (data.getIssuetime1() == null || data.getIssuetime1().equals("")) {
                    data.setIssuetime(new Date());
                }
            } else if (data.getIssuetime1() == null || data.getIssuetime1().equals("")) {

            } else {
                data.setIssuetime(sdf.parse(data.getIssuetime1()));
            }

            if (data.getDeadline1().equals("")) {

            } else {
                data.setDeadline(sdf.parse(data.getDeadline1()));
            }

            if (data.getIssued() == null || data.getIssued().equals("null")) {
                data.setIssued(false);
            }
            if (data.getStates() == null || data.getStates().equals("null")) {
                data.setStates(false);
            }
            String gid = bjxxClassMaterialProjectService.add(data, userEmployee.getUid());

            return "redirect:addInInt";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加项目信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "班级项目信息", moduleName = "班级项目管理", method = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            for (String id : idList) {
                BjxxClassMaterialProject data = new BjxxClassMaterialProject();
                data.setXmid(Integer.valueOf(id));
                bjxxClassMaterialProjectService.delete(data);

                BjxxClassMaterialRange bjxxClassMaterialRange = new BjxxClassMaterialRange();
                bjxxClassMaterialRange.setParentid(Integer.valueOf(id));
                bjxxClassMaterialRangeService.delete(bjxxClassMaterialRange);
            }

            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "班级项目信息", moduleName = "班级项目管理", method = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(ModelMap model, HttpServletRequest request,
                         BjxxClassMaterialProject data) {
        try {

            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":"
                              + request.getServerPort() + path;
            /*  UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);*/
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            if (data.getIssued() == true) {
                if (data.getIssuetime1() == null || data.getIssuetime1().equals("")) {
                    data.setIssuetime(new Date());
                } else {
                    data.setIssuetime(sdf.parse(data.getIssuetime1()));
                }
            } else if (data.getIssuetime1() == null || data.getIssuetime1().equals("")) {

            } else {
                data.setIssuetime(sdf.parse(data.getIssuetime1()));
            }

            if (data.getDeadline1().equals("")) {

            } else {
                data.setDeadline(sdf.parse(data.getDeadline1()));
            }

            if (data.getIssued() == null || data.getIssued().equals("null")) {
                data.setIssued(false);
            }
            if (data.getStates() == null || data.getStates().equals("null")) {
                data.setStates(false);
            }

            bjxxClassMaterialProjectService.update(data, null, basePath);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:index";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/validation")
    public @ResponseBody Map<String, Object> validation(@RequestParam(value = "xmmc") String xmmc,
                                                        @RequestParam(value = "id") String id,
                                                        HttpServletRequest request,
                                                        HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            BjxxClassMaterialProject data = new BjxxClassMaterialProject();
            data.setXmid(id.equals("null") || id.equals("") ? null : Integer.valueOf(id));
            data.setXmmc(xmmc.trim());
            int count = bjxxClassMaterialProjectService.validation(data);
            if (count == -99) {
                dataMap.put("msg", "-99");
            } else if (count == 0) {
                dataMap.put("msg", "0");
            } else {
                dataMap.put("msg", "-1");
            }
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("msg", "-99");
        }
        return dataMap;
    }

    @RequestMapping(value = "/index_bzr")
    public String index_bzr(ModelMap model, HttpServletRequest request) {

        return "bjxxClassMaterialProject/BjxxClassMaterialProjectList_bzr";
    }

    @RequestMapping(value = "/List_bzr")
    @ResponseBody
    public ResponseResult List_bzr(ModelMap model, HttpServletRequest request,
                                   @RequestParam(value = "rows", required = false) String pageSize,
                                   @RequestParam(value = "page", required = false) String currentPage,
                                   BjxxClassMaterialProject data) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);

            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "p.createTime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            data.setEmpId(userEmployee.getEmid());
            PaginationBean<BjxxClassMaterialProject> paginationBean = bjxxClassMaterialProjectService
                .queryPageList_bzr(data, page);
            ResponseResult result = new ResponseResult();

            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<BjxxClassMaterialProject>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());

            return result;

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 下载
     * 
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export")
    public @ResponseBody String exportStudentjobList(HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     BjxxClassMaterialProject data,
                                                     @RequestParam("bodyData") String bodyData,
                                                     ModelMap model) throws Exception {
        try {

            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            List<BjxxClassMaterialProject> datalist = bjxxClassMaterialProjectService.export(data);

            /* List<BjxxClassMaterialProject> datalist = JSONArray.parseArray(bodyData,
                BjxxClassMaterialProject.class);*/

            String[][] title_name = { { "材料名称", "排序次序", "项目状态", "发布状态", "提交期限", "创建时间", "发布时间" } };
            String[] title_style = { "hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20",
                                     "st_12_n_20", "st_12_n_20", "st_12_n_20" };
            String fileName = "班级项目管理信息";
            String[] remark = { "" };
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if (datalist != null && !datalist.isEmpty()) {
                for (BjxxClassMaterialProject r : datalist) {
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("xmmc", r.getXmmc());
                    map.put("orders", r.getOrders());
                    map.put("states", r.getStates() == false ? "无效" : "有效");
                    map.put("issued", r.getIssued() == false ? "未发布" : "已发布");
                    if (r.getDeadline() == null) {
                        map.put("deadline", null);
                    } else {
                        map.put("deadline", sdf.format(r.getDeadline()));
                    }
                    if (r.getCreatetime() == null) {
                        map.put("createtime", null);
                    } else {
                        map.put("createtime", sdf.format(r.getCreatetime()));
                    }
                    if (r.getIssuetime() == null) {
                        map.put("issuetime", null);
                    } else {
                        map.put("issuetime", sdf.format(r.getIssuetime()));
                    }
                    list.add(map);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark,
                fileName, list);
            try {
                String filenameConvert = "班级项目管理信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(),
                        "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
                model.addAttribute(Constant.EXPTION_MSG_KEY, e);
                return "error/error";
            }
        } catch (RPCException e) {
            LOGGER.error("获得班级管理项目信息 export[{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return null;
    }

    /**
     * 下载
     * 
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export_bzr")
    public @ResponseBody String export_bzr(HttpServletRequest request, HttpServletResponse response,
                                           BjxxClassMaterialProject data,
                                           @RequestParam("bodyData") String bodyData,
                                           ModelMap model) throws Exception {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);

            BaseController.setSortByColumn(request, "p.createTime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            data.setEmpId(userEmployee.getEmid());
            List<BjxxClassMaterialProject> datalist = bjxxClassMaterialProjectService
                .export_bzr(data);

            /*   List<BjxxClassMaterialProject> datalist = JSONArray.parseArray(bodyData,
                BjxxClassMaterialProject.class);*/

            String[][] title_name = { { "材料名称", "排序次序", "发布状态", "提交期限", "创建时间", "发布时间" } };
            String[] title_style = { "hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20",
                                     "st_12_n_20", "st_12_n_20" };
            String fileName = "班主任材料项目管理信息";
            String[] remark = { "" };
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if (datalist != null && !datalist.isEmpty()) {
                for (BjxxClassMaterialProject r : datalist) {
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("xmmc", r.getXmmc());
                    map.put("orders", r.getOrders());

                    map.put("issued", r.getIssued() == false ? "未发布" : "已发布");
                    if (r.getDeadline() == null) {
                        map.put("deadline", null);
                    } else {
                        map.put("deadline", sdf.format(r.getDeadline()));
                    }
                    if (r.getCreatetime() == null) {
                        map.put("createtime", null);
                    } else {
                        map.put("createtime", sdf.format(r.getCreatetime()));
                    }
                    if (r.getIssuetime() == null) {
                        map.put("issuetime", null);
                    } else {
                        map.put("issuetime", sdf.format(r.getIssuetime()));
                    }
                    list.add(map);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark,
                fileName, list);
            try {
                String filenameConvert = "班主任材料项目管理信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(),
                        "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
                model.addAttribute(Constant.EXPTION_MSG_KEY, e);
                return "error/error";
            }
        } catch (RPCException e) {
            LOGGER.error("获得班级管理项目信息 export[{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return null;
    }
}
